package edu.uoc.tdp.pac4.client.maintenance;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import edu.uoc.tdp.pac4.beans.Rol;
import edu.uoc.tdp.pac4.beans.Sex;
import edu.uoc.tdp.pac4.beans.Usuari;
import edu.uoc.tdp.pac4.client.ClientConnectionHelper;
import edu.uoc.tdp.pac4.common.MantenimentInterface;
import edu.uoc.tdp.pac4.common.util.LanguageUtils;

public class UserListWindow extends JPanel{

	private static final String ALL_ROL = "---";
	private ClientConnectionHelper connectionHelper_;
	private MantenimentInterface maintenance;
	private JTextField txtLogin;
	private JTextField txtName;
	private JTextField txtSurname;
	private JTextField txtNif;
	private JTextField txtEmail;
	private JTextField txtStart;
	private JTextField txtEnd;
	private JTextField txtBirthdaystart;
	private JTextField txtBirthdayend;
	private JComboBox cbRol;
	private ButtonGroup groupSex = new ButtonGroup();
	private ButtonGroup groupStatus = new ButtonGroup();

	private JTable tbUserList;

	
	public UserListWindow(final ClientConnectionHelper connectionHelper_) {

		this.connectionHelper_ = connectionHelper_;
		this.maintenance=connectionHelper_.getMaintenanceManager();
		
		
		//setTitle("User List");
		//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//setBounds(100, 100, 650, 658);
		setBorder(new TitledBorder(null,
				LanguageUtils
						.getMessage("main.menu.maintenance.user"),
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		setLayout(null);
		
		
		//getContentPane().add
		JPanel panel = new JPanel();
		panel.setBounds(12, 12, 514, 288);
		panel.setLayout(null);
		add(panel);
		//add(panel, BorderLayout.NORTH);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane.setBounds(6, 300, 619, 120);
		add(scrollPane);
		//scrollPane.setMaximumSize( new Dimension(200, 200));

		JPanel panel_1 = new JPanel();
		panel_1.setBounds(6, 450, 619, 37);
		add(panel_1,BorderLayout.SOUTH);

		
		/////
		
		GridBagLayout gbl_panel = new GridBagLayout();
		gbl_panel.columnWidths = new int[]{147, 35, 114, 0};
		gbl_panel.rowHeights = new int[]{0, 19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
		gbl_panel.columnWeights = new double[]{0.0, 1.0, 1.0, Double.MIN_VALUE};
		gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		panel.setLayout(gbl_panel);

		
		//register
		JLabel lblRegister = new JLabel(LanguageUtils.getMessage("client.maintenance.usermanag.labelInactivityDate"));
		GridBagConstraints gbc_lblRegister = new GridBagConstraints();
		gbc_lblRegister.insets = new Insets(0, 0, 5, 5);
		gbc_lblRegister.anchor = GridBagConstraints.WEST;
		gbc_lblRegister.gridx = 0;
		gbc_lblRegister.gridy = 0;
		panel.add(lblRegister, gbc_lblRegister);
		
		txtStart = new JTextField();
		//txtStart.setText("start");
		GridBagConstraints gbc_txtStart = new GridBagConstraints();
		gbc_txtStart.insets = new Insets(0, 0, 5, 5);
		gbc_txtStart.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtStart.gridx = 1;
		gbc_txtStart.gridy = 0;
		panel.add(txtStart, gbc_txtStart);
		txtStart.setColumns(10);
		
		txtEnd = new JTextField ();
		//txtEnd.setText("end");
		GridBagConstraints gbc_txtEnd = new GridBagConstraints();
		gbc_txtEnd.insets = new Insets(0, 0, 5, 0);
		gbc_txtEnd.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtEnd.gridx = 2;
		gbc_txtEnd.gridy = 0;
		panel.add(txtEnd, gbc_txtEnd);
		txtEnd.setColumns(10);

		//login
		JLabel lblLogin = new JLabel(LanguageUtils.getMessage("client.maintenance.usermanag.labelLogin"));
		GridBagConstraints gbc_lblLogin = new GridBagConstraints();
		gbc_lblLogin.insets = new Insets(0, 0, 5, 5);
		gbc_lblLogin.anchor = GridBagConstraints.WEST;
		gbc_lblLogin.gridx = 0;
		gbc_lblLogin.gridy = 1;
		panel.add(lblLogin, gbc_lblLogin);
		
		txtLogin = new JTextField();
		//txtLogin.setText("login");
		GridBagConstraints gbc_txtLogin = new GridBagConstraints();
		gbc_txtLogin.insets = new Insets(0, 0, 5, 5);
		gbc_txtLogin.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtLogin.gridx = 1;
		gbc_txtLogin.gridy = 1;
		panel.add(txtLogin, gbc_txtLogin);
		txtLogin.setColumns(10);
		
		//name
		JLabel lblName = new JLabel(LanguageUtils.getMessage("client.maintenance.usermanag.labelName"));
		GridBagConstraints gbc_lblName = new GridBagConstraints();
		gbc_lblName.insets = new Insets(0, 0, 5, 5);
		gbc_lblName.anchor = GridBagConstraints.WEST;
		gbc_lblName.gridx = 0;
		gbc_lblName.gridy = 2;
		panel.add(lblName, gbc_lblName);
		
		txtName = new JTextField();
		//txtName.setText("name");
		GridBagConstraints gbc_txtName = new GridBagConstraints();
		gbc_txtName.insets = new Insets(0, 0, 5, 5);
		gbc_txtName.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtName.gridx = 1;
		gbc_txtName.gridy = 2;
		panel.add(txtName, gbc_txtName);
		txtName.setColumns(10);
		
		//surname
		JLabel lblSurname = new JLabel(LanguageUtils.getMessage("client.maintenance.usermanag.labelSurnames"));
		GridBagConstraints gbc_lblSurname = new GridBagConstraints();
		gbc_lblSurname.insets = new Insets(0, 0, 5, 5);
		gbc_lblSurname.anchor = GridBagConstraints.WEST;
		gbc_lblSurname.gridx = 0;
		gbc_lblSurname.gridy = 3;
		panel.add(lblSurname, gbc_lblSurname);
		
		txtSurname = new JTextField();
		//txtSurname.setText("surname");
		GridBagConstraints gbc_txtSurname = new GridBagConstraints();
		gbc_txtSurname.insets = new Insets(0, 0, 5, 5);
		gbc_txtSurname.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtSurname.gridx = 1;
		gbc_txtSurname.gridy = 3;
		panel.add(txtSurname, gbc_txtSurname);
		txtSurname.setColumns(10);
		
		//nif
		JLabel lblNif = new JLabel(LanguageUtils.getMessage("client.maintenance.usermanag.labelNIF"));
		GridBagConstraints gbc_lblNif = new GridBagConstraints();
		gbc_lblNif.insets = new Insets(0, 0, 5, 5);
		gbc_lblNif.anchor = GridBagConstraints.WEST;
		gbc_lblNif.gridx = 0;
		gbc_lblNif.gridy = 4;
		panel.add(lblNif, gbc_lblNif);
		
		txtNif = new JTextField();
		//txtNif.setText("nif");
		GridBagConstraints gbc_txtNif = new GridBagConstraints();
		gbc_txtNif.insets = new Insets(0, 0, 5, 5);
		gbc_txtNif.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtNif.gridx = 1;
		gbc_txtNif.gridy = 4;
		panel.add(txtNif, gbc_txtNif);
		txtNif.setColumns(10);
		
		//birthday
		JLabel lblBirthday = new JLabel(LanguageUtils.getMessage("client.maintenance.usermanag.labelBirthday"));
		GridBagConstraints gbc_lblBirthday = new GridBagConstraints();
		gbc_lblBirthday.insets = new Insets(0, 0, 5, 5);
		gbc_lblBirthday.anchor = GridBagConstraints.WEST;
		gbc_lblBirthday.gridx = 0;
		gbc_lblBirthday.gridy = 5;
		panel.add(lblBirthday, gbc_lblBirthday);
		
		txtBirthdaystart = new JTextField();
		//txtBirthdaystart.setText("birthdayStart");
		GridBagConstraints gbc_txtBirthdaystart = new GridBagConstraints();
		gbc_txtBirthdaystart.insets = new Insets(0, 0, 5, 5);
		gbc_txtBirthdaystart.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtBirthdaystart.gridx = 1;
		gbc_txtBirthdaystart.gridy = 5;
		panel.add(txtBirthdaystart, gbc_txtBirthdaystart);
		txtBirthdaystart.setColumns(10);
		
		txtBirthdayend = new JTextField();
		//txtBirthdayend.setText("birthdayEnd");
		GridBagConstraints gbc_txtBirthdayend = new GridBagConstraints();
		gbc_txtBirthdayend.insets = new Insets(0, 0, 5, 0);
		gbc_txtBirthdayend.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtBirthdayend.gridx = 2;
		gbc_txtBirthdayend.gridy = 5;
		panel.add(txtBirthdayend, gbc_txtBirthdayend);
		txtBirthdayend.setColumns(10);
		
		//email
		JLabel lblEmail = new JLabel(LanguageUtils.getMessage("client.maintenance.usermanag.labelEmail"));
		GridBagConstraints gbc_lblEmail = new GridBagConstraints();
		gbc_lblEmail.insets = new Insets(0, 0, 5, 5);
		gbc_lblEmail.anchor = GridBagConstraints.WEST;
		gbc_lblEmail.gridx = 0;
		gbc_lblEmail.gridy = 6;
		panel.add(lblEmail, gbc_lblEmail);
		
		txtEmail = new JTextField();
		//txtEmail.setText("email");
		GridBagConstraints gbc_txtEmail = new GridBagConstraints();
		gbc_txtEmail.insets = new Insets(0, 0, 5, 5);
		gbc_txtEmail.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtEmail.gridx = 1;
		gbc_txtEmail.gridy = 6;
		panel.add(txtEmail, gbc_txtEmail);
		txtEmail.setColumns(10);
		
		//rol
		JLabel lblRol = new JLabel(LanguageUtils.getMessage("client.maintenance.usermanag.labelRol"));
		GridBagConstraints gbc_lblRol = new GridBagConstraints();
		gbc_lblRol.insets = new Insets(0, 0, 5, 5);
		gbc_lblRol.anchor = GridBagConstraints.WEST;
		gbc_lblRol.gridx = 0;
		gbc_lblRol.gridy = 7;
		panel.add(lblRol, gbc_lblRol);
		
		cbRol = new JComboBox();
		GridBagConstraints gbc_cbRol = new GridBagConstraints();
		gbc_cbRol.insets = new Insets(0, 0, 5, 5);
		gbc_cbRol.fill = GridBagConstraints.HORIZONTAL;
		gbc_cbRol.gridx = 1;
		gbc_cbRol.gridy = 7;
		panel.add(cbRol, gbc_cbRol);
		cbRol.addItem(ALL_ROL);
		cbRol.setSelectedItem(ALL_ROL);
		cbRol.addItem(Rol.Administrador);
		cbRol.addItem(Rol.Alumne);
		cbRol.addItem(Rol.Personal_Academic);
		cbRol.addItem(Rol.Professor);
		
		
		//sex
		JLabel lblSex = new JLabel(LanguageUtils.getMessage("client.maintenance.usermanag.labelSex"));
		GridBagConstraints gbc_lblSex = new GridBagConstraints();
		gbc_lblSex.anchor = GridBagConstraints.WEST;
		gbc_lblSex.insets = new Insets(0, 0, 5, 5);
		gbc_lblSex.gridx = 0;
		gbc_lblSex.gridy = 8;
		panel.add(lblSex, gbc_lblSex);

		
		final JRadioButton rdbtnMale = new JRadioButton(Sex.Home.name());
		GridBagConstraints gbc_rdbtnMale = new GridBagConstraints();
		gbc_rdbtnMale.anchor = GridBagConstraints.WEST;
		gbc_rdbtnMale.insets = new Insets(0, 0, 5, 5);
		gbc_rdbtnMale.gridx = 1;
		gbc_rdbtnMale.gridy = 8;
		panel.add(rdbtnMale, gbc_rdbtnMale);
		
		final JRadioButton rdbtnFemale = new JRadioButton(Sex.Dona.name());
		GridBagConstraints gbc_rdbtnFemale = new GridBagConstraints();
		gbc_rdbtnFemale.anchor = GridBagConstraints.WEST;
		gbc_rdbtnFemale.insets = new Insets(0, 0, 5, 0);
		gbc_rdbtnFemale.gridx = 2;
		gbc_rdbtnFemale.gridy = 8;
		panel.add(rdbtnFemale, gbc_rdbtnFemale);

		groupSex.add(rdbtnMale);
		groupSex.add(rdbtnFemale);

		//status
		JLabel lblStatus = new JLabel(LanguageUtils.getMessage("client.maintenance.usermanag.labelStatus"));
		GridBagConstraints gbc_lblStatus = new GridBagConstraints();
		gbc_lblStatus.anchor = GridBagConstraints.WEST;
		gbc_lblStatus.insets = new Insets(0, 0, 5, 5);
		gbc_lblStatus.gridx = 0;
		gbc_lblStatus.gridy = 9;
		panel.add(lblStatus, gbc_lblStatus);
		
		final JRadioButton rdbtnActive = new JRadioButton("active");
		GridBagConstraints gbc_rdbtnActive = new GridBagConstraints();
		gbc_rdbtnActive.anchor = GridBagConstraints.WEST;
		gbc_rdbtnActive.insets = new Insets(0, 0, 5, 5);
		gbc_rdbtnActive.gridx = 1;
		gbc_rdbtnActive.gridy = 9;
		panel.add(rdbtnActive, gbc_rdbtnActive);
		
		final JRadioButton rdbtnInactive = new JRadioButton("inactive");
		GridBagConstraints gbc_rdbtnInactive = new GridBagConstraints();
		gbc_rdbtnInactive.insets = new Insets(0, 0, 5, 0);
		gbc_rdbtnInactive.anchor = GridBagConstraints.WEST;
		gbc_rdbtnInactive.gridx = 2;
		gbc_rdbtnInactive.gridy = 9;
		panel.add(rdbtnInactive, gbc_rdbtnInactive);

		groupStatus.add(rdbtnActive);
		groupStatus.add(rdbtnInactive);
		
		JButton btnSearch = new JButton(LanguageUtils.getMessage("client.maintenance.usermanag.btnSearch")); 
		GridBagConstraints gbc_btnSearch = new GridBagConstraints();
		gbc_btnSearch.insets = new Insets(0, 0, 0, 5);
		gbc_btnSearch.gridx = 0;
		gbc_btnSearch.gridy = 10;
		panel.add(btnSearch, gbc_btnSearch);
		btnSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					findUsers();
				} catch (RemoteException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}

		});
		btnSearch.setHorizontalAlignment(SwingConstants.LEFT);
		
		JButton btnClear = new JButton(LanguageUtils.getMessage("client.maintenance.usermanag.btnClear"));
		btnClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				txtLogin.setText("");
				txtName.setText("");
				txtSurname.setText("");
				txtNif.setText("");
				txtEmail.setText("");
				txtStart.setText("");
				txtEnd.setText("");
				txtBirthdaystart.setText("");
				txtBirthdayend.setText("");
				cbRol.setSelectedIndex(0);
				groupSex.clearSelection();
				groupStatus.clearSelection();
			}
		});
		btnClear.setHorizontalAlignment(SwingConstants.LEFT);
		GridBagConstraints gbc_btnClear = new GridBagConstraints();
		gbc_btnClear.anchor = GridBagConstraints.WEST;
		gbc_btnClear.insets = new Insets(0, 0, 0, 5);
		gbc_btnClear.gridx = 1;
		gbc_btnClear.gridy = 10;
		panel.add(btnClear, gbc_btnClear);
		
		
		
		
		tbUserList= new JTable();
		
		scrollPane.add(tbUserList);
		scrollPane.setViewportView(tbUserList);
		
		JButton btnCreate = new JButton(LanguageUtils.getMessage("client.maintenance.usermanag.btnCreate"));
		btnCreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				UserCreateWindow createWindow = new UserCreateWindow(connectionHelper_);
				createWindow.setVisible(true);
			}
		});
		panel_1.add(btnCreate);

		final JButton btnEdit = new JButton(LanguageUtils.getMessage("client.maintenance.usermanag.btnEdit"));
		btnEdit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				int i = tbUserList.getSelectedRow();
				TableModel model2 = tbUserList.getModel();
				String identificador = (String) model2.getValueAt(i, 0);
				try {
					Usuari usuari = maintenance.findUserById(identificador);
					UserCreateWindow createWindow = new UserCreateWindow(usuari, connectionHelper_);
					createWindow.setVisible(true);				
					
				} catch (RemoteException e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(null, e1.getMessage(), null,
							JOptionPane.INFORMATION_MESSAGE);			
				} catch (RuntimeException e1) {
					e1.printStackTrace();
					JOptionPane.showMessageDialog(null, e1.getMessage(), null,
							JOptionPane.INFORMATION_MESSAGE);			
				}
				
			}
		});
		btnEdit.setEnabled(false);
		panel_1.add(btnEdit);

		
		tbUserList.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				int selectedRow = tbUserList.getSelectedRow();
	            System.out.println("Selected row:" + selectedRow);
	            if (selectedRow == -1) {
	                System.out
	                        .println("Select a row in the table before clicking \"Delete\"");
	                return;
	            } 
	            btnEdit.setEnabled(true);
			}
		});

		


	}


	protected void findUsers() throws RemoteException{
		
		Usuari usuariFilter=new Usuari();
		usuariFilter.setNIF("".equals(txtNif.getText())?null:txtNif.getText());
		usuariFilter.setNombre("".equals(txtName.getText())?null:txtName.getText());
		usuariFilter.setApellidos("".equals(txtSurname.getText())?null:txtSurname.getText());		
		//usuariFilter.setNacimiento(dateFormat.parse(txtBirthday.getText()));
		usuariFilter.setUsuariActiu(getSelection(groupStatus)==null?null:"active".equals(getSelection(groupStatus).getText()));
		//usuariFilter.setDataBaixa(getSelection(groupStatus)==null?null:("active".equals(getSelection(groupStatus).getText()))?null:new Date());
		usuariFilter.setEmail("".equals(txtEmail.getText())?null:txtEmail.getText());
		usuariFilter.setSexe(getSelection(groupSex)==null?null:Sex.valueOf(getSelection(groupSex).getText()));
		usuariFilter.setRol(ALL_ROL.equals(cbRol.getSelectedItem())?null:(Rol)cbRol.getSelectedItem());
		usuariFilter.setLogin("".equals(txtLogin.getText())?null:txtLogin.getText());
		//usuariFilter.setContrasenya(txtPassword.getText());
		//usuariFilter.setUsuariActiu("active".equals(getSelection(groupStatus).getText()));

		List<Usuari> usuaris = this.maintenance.findUsers(usuariFilter);

		Object[] columnNames = new String[] {
				LanguageUtils.getMessage("usuari.nif"),
				LanguageUtils.getMessage("usuari.login"),
				LanguageUtils.getMessage("usuari.name"),
				LanguageUtils.getMessage("usuari.surname"),
				LanguageUtils.getMessage("usuari.rol")
				};
		
		Object[][] data = new Object[usuaris.size()][columnNames.length];

		for (int i = 0; i < data.length; i++) {
			Usuari usuari = usuaris.get(i);
			data[i] = new Object[] { usuari.getNIF(), usuari.getLogin(),
					usuari.getNombre(), usuari.getApellidos(),
					usuari.getRol() };
		}

		TableModel model = new DefaultTableModel(data, columnNames);
		tbUserList.setModel(model);
		
		
	}
	
	
	
	
	  public static JRadioButton getSelection(ButtonGroup group) {
		for (Enumeration e = group.getElements(); e.hasMoreElements();) {
			JRadioButton b = (JRadioButton) e.nextElement();
			if (b.getModel() == group.getSelection()) {
				return b;
			}
		}
		return null;
	  }

}
